<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Excel文件合并工具</title>
    <link href="js/bootstrap.min.css" rel="stylesheet">
    <style>
        .upload-area {
            border: 2px dashed #ccc;
            border-radius: 8px;
            padding: 20px;
            text-align: center;
            margin: 20px 0;
            background-color: #f8f9fa;
        }
        .upload-area.dragover {
            background-color: #e9ecef;
            border-color: #0d6efd;
        }
    </style>
</head>
<body>
    <div class="container mt-5">
        <h2 class="text-center mb-4">Excel文件合并工具</h2>
        
        <div class="upload-area" id="dropZone">
            <div class="mb-3">
                <p class="text-muted">拖拽Excel文件到这里，或者点击下方按钮选择文件</p>
                <input type="file" class="form-control" id="fileInput" multiple accept=".xlsx,.xls">
            </div>
        </div>

        <div class="selected-files mt-3">
            <h5>已选择的文件：</h5>
            <ul class="list-group" id="fileList"></ul>
        </div>

        <div class="text-center mt-4">
            <button class="btn btn-primary" id="mergeBtn" disabled>合并文件</button>
        </div>

        <div class="alert alert-info mt-4" role="alert" style="display: none" id="statusMsg">
        </div>
    </div>

    <script src="js/bootstrap.bundle.min.js"></script>
    <script>
        const dropZone = document.getElementById('dropZone');
        const fileInput = document.getElementById('fileInput');
        const fileList = document.getElementById('fileList');
        const mergeBtn = document.getElementById('mergeBtn');
        const statusMsg = document.getElementById('statusMsg');

        // 拖拽相关事件
        ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
            dropZone.addEventListener(eventName, preventDefaults, false);
        });

        function preventDefaults(e) {
            e.preventDefault();
            e.stopPropagation();
        }

        ['dragenter', 'dragover'].forEach(eventName => {
            dropZone.addEventListener(eventName, highlight, false);
        });

        ['dragleave', 'drop'].forEach(eventName => {
            dropZone.addEventListener(eventName, unhighlight, false);
        });

        function highlight(e) {
            dropZone.classList.add('dragover');
        }

        function unhighlight(e) {
            dropZone.classList.remove('dragover');
        }

        dropZone.addEventListener('drop', handleDrop, false);

        function handleDrop(e) {
            const dt = e.dataTransfer;
            const files = dt.files;
            handleFiles(files);
        }

        fileInput.addEventListener('change', function(e) {
            handleFiles(this.files);
        });

        function handleFiles(files) {
            updateFileList(files);
            mergeBtn.disabled = fileList.children.length === 0;
        }

        function updateFileList(files) {
            fileList.innerHTML = '';
            Array.from(files).forEach(file => {
                const li = document.createElement('li');
                li.className = 'list-group-item';
                li.textContent = file.name;
                fileList.appendChild(li);
            });
        }

        mergeBtn.addEventListener('click', async () => {
            const files = fileInput.files;
            if (files.length === 0) return;

            const formData = new FormData();
            Array.from(files).forEach(file => {
                formData.append('files', file);
            });

            mergeBtn.disabled = true;
            statusMsg.style.display = 'block';
            statusMsg.textContent = '正在处理文件，请稍候...';

            try {
                // Step 1: 调用 upload 接口
                // const uploadResponse = await fetch('http://localhost:8089/excel/upload', {
                const uploadResponse = await fetch('/excel/upload', {
                    method: 'POST',
                    body: formData
                });

                console.log(uploadResponse);

                if (uploadResponse.ok) {
                    // Step 2: 调用 download 接口
                    // const downloadResponse = await fetch('http://localhost:8089/excel/download');
                    const downloadResponse = await fetch('/excel/download');

                    if (downloadResponse.ok) {
                        // Step 3: 处理 download 响应，触发文件下载
                        const blob = await downloadResponse.blob();
                        const url = window.URL.createObjectURL(blob);
                        const a = document.createElement('a');
                        a.href = url;
                        a.download = '试验数据统计表.xlsx';
                        document.body.appendChild(a);
                        a.click();
                        window.URL.revokeObjectURL(url);
                        statusMsg.textContent = '文件合并成功并已下载！';
                        statusMsg.className = 'alert alert-success mt-4';
                    } else {
                        // 处理 download 接口非 2xx 状态码的情况
                        const errorText = await downloadResponse.text();
                        console.error('Download failed with non-OK status:', downloadResponse.status, errorText);
                        throw new Error('下载失败');
                    }
                } else {
                    // 处理 upload 接口非 2xx 状态码的情况
                    const errorText = await uploadResponse.text();
                    console.error('Upload failed with non-OK status:', uploadResponse.status, errorText);
                    throw new Error('上传失败');
                }
            } catch (error) {
                console.error('Request failed:', error);
                statusMsg.textContent = '操作失败，请重试！';
                statusMsg.className = 'alert alert-danger mt-4';
            } finally {
                mergeBtn.disabled = false;
            }
        });

    </script>
</body>
</html>